package com.koushikdutta.ion.loader;

import com.example.ohosasynclibrary.async.future.Future;
import com.example.ohosasynclibrary.async.future.SimpleFuture;
import com.koushikdutta.ion.ImageUtil;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.ResponseServedFrom;
import com.koushikdutta.ion.bitmap.BitmapInfo;
import ohos.agp.utils.Point;
import ohos.app.Context;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;

import java.io.File;

/**
 * Created by koush on 11/3/13.
 */
public class PackageIconLoader extends SimpleLoader {
    @Override
    public Future<BitmapInfo> loadBitmap(Context context, final Ion ion, final String key, final String uri, int resizeWidth, int resizeHeight, boolean animateGif) {
        if (uri == null || !uri.startsWith("package:"))
            return null;

        final SimpleFuture<BitmapInfo> ret = new SimpleFuture<BitmapInfo>();
        Ion.getBitmapLoadExecutorService().execute(new Runnable() {
            @Override
            public void run() {
                try {
//                    final URI request = URI.create(uri);
//                    String pkg = request.getHost();
//                    PackageManager pm = ion.getContext().getPackageManager();
//                    Bitmap bmp = ((BitmapDrawable) pm.getPackageInfo(pkg, 0).applicationInfo.loadIcon(pm)).getBitmap();



//                    PixelMap bmp = getPixelMapByFile(new File(ion.getContext().getApplicationInfo().getIcon()));

                    PixelMap bmp = ImageUtil.getPixelMapByUri(context, uri);

                    if (bmp == null)
                        throw new Exception("package icon failed to load");
                    BitmapInfo info = new BitmapInfo(key, null, bmp, new Point(bmp.getImageInfo().size.width, bmp.getImageInfo().size.height));
                    info.servedFrom = ResponseServedFrom.LOADED_FROM_CACHE;
                    ret.setComplete(info);
                } catch (Exception e) {
                    ret.setComplete(e);
                }
            }
        });

        return ret;
    }

    private PixelMap getPixelMapByFile(File file) {
        if (file == null || !file.exists()) {
            return null;
        }
        ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
        srcOpts.formatHint = "image/*";
        ImageSource imageSource = ImageSource.create(file.getAbsoluteFile(), srcOpts);


        ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
        decodingOpts.desiredSize = new Size(0, 0);
        decodingOpts.desiredRegion = new Rect(0, 0, 0, 0);
        decodingOpts.desiredPixelFormat = PixelFormat.ARGB_8888;
        return imageSource.createPixelmap(decodingOpts);
    }
}
